#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<iostream>
using namespace std;
void Usage(std::string proc)
{
  cout <<"Usage\n\t " << proc << " server_ip " << "server_port" << endl;
  exit(1);
}
int main(int argc,char* argv[])
{
  if(argc != 3)
  {
    Usage(argv[0]);
  }
  int sock = socket(AF_INET,SOCK_STREAM,0);
  cout << "socket success" << endl; 
  std::string ip = argv[1];
  uint16_t port = atoi(argv[2]);
  struct sockaddr_in server;
  socklen_t len = sizeof(server);
  memset(&server,0,sizeof(server));
  server.sin_family = AF_INET;
  server.sin_port = htons(port);
  server.sin_addr.s_addr = inet_addr(ip.c_str());
  if(connect(sock,(struct sockaddr*)&server,len) < 0)
  {
    cerr << "connect err" << endl;
  }
  for(;;)
  {
    //从键盘获取用户输入，作为信息发送给服务端，然后读取服务端的响应
    char msg[1024] = {0};
    cout <<"Please Enter:";
    fgets(msg,sizeof(msg)-1,stdin);
    msg[strlen(msg)-1] = 0;//注意：从键盘当中读取会把\n也读到   -> hello\n\0  ->所以要把\n的位置为\0
    write(sock,msg,sizeof(msg)-1);//写入的时候不写\0，因为写入关心的是内容，而\0是C语言字符串的结束标识符 
    //读取服务端的响应
    char resp[1024] = {0};
    ssize_t n = read(sock,resp,sizeof(resp)-1);
    if(n > 0)
    {
      resp[n] = 0;
      cout <<"server #" << resp << endl;
    }
  }
  return 0;
}
